package com.bigchun.seeland.wxapi;


import java.util.HashMap;

import bean.ContentDataBean;
import myapp.MyApp;
import util.MyLog;
import util.PreferenceUtil;
import util.RequestManager;

import org.json.JSONException;
import org.json.JSONObject;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.WindowManager;
import android.widget.Toast;

import com.bigchun.seeland.LoginInputmsgActivity;
import com.bigchun.seeland.MainActivity;
import com.bigchun.seeland.R;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.ShowMessageFromWX;
import com.tencent.mm.opensdk.modelmsg.WXAppExtendObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;


public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    public static final String action = "jason.broadcast.action";
    private MyApp m = null;
    // IWXAPI 是第三方app和微信通信的openapi接口
    private IWXAPI api;
    private String openid;
    private IWXAPI iwxapi;
    private Context context;
    private String openidWX = "";
    private MyApp myApp;
    private JSONObject dataFB;
    private String status = "0";
    private String apptype;
    private String textData;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getSupportActionBar().hide();
        // 隐藏状态栏
        myApp = (MyApp) getApplicationContext();
        context = this;
        SharedPreferences sharedPreferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        String token = sharedPreferences.getString("token", "");
        apptype = sharedPreferences.getString("apptype", "0");
        textData = sharedPreferences.getString("textData", "");
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //接收到分享以及登录的intent传递handleIntent方法，处理结果
        iwxapi = WXAPIFactory.createWXAPI(this, getString(R.string.weixin_appid), false);
        iwxapi.handleIntent(getIntent(), this);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    // 微信发送请求到第三方应用时，会回调到该方法
    @Override
    public void onReq(BaseReq req) {
        switch (req.getType()) {
            case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
                goToGetMsg();
                break;
            case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
                goToShowMsg((ShowMessageFromWX.Req) req);
                break;
            case ConstantsAPI.COMMAND_LAUNCH_BY_WX:
                Toast.makeText(this, "111", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }
    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    @Override
    public void onResp(BaseResp resp) {
        MyLog.e("微信","分享成功   "+resp.toString());
        openid = resp.openId;
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                if(resp.toString().contains("com.tencent.mm.opensdk.modelmsg.SendMessageToWX$Resp")){
                    MyLog.e("微信","分享成功");
                    ContentDataBean.DataBean textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {}.getType());
                    if (textContent != null) {
                        Toast.makeText(WXEntryActivity.this, textContent.getShare_success(), Toast.LENGTH_LONG).show();
                    }
                    finish();
                }else {
                    SendAuth.Resp newResp = (SendAuth.Resp) resp;
                    String wxcode = newResp.code;
                    MyLog.e("微信","登陆成功"+wxcode);
                    getWxOpenId(wxcode);
//                    getcode(wxcode);
//                    getInformation(newResp.code);
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                if(resp.toString().contains("com.tencent.mm.opensdk.modelmsg.SendMessageToWX$Resp")){
                    MyLog.e("微信","分享取消");
                    ContentDataBean.DataBean textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {}.getType());
                    if (textContent != null) {
                        Toast.makeText(WXEntryActivity.this, textContent.getShare_cancle(), Toast.LENGTH_LONG).show();
                    }
                    finish();
                }else {
                    MyLog.e("微信","登录取消");
//                    Toast.makeText(WXEntryActivity.this,getString(R.string.login_cancle),Toast.LENGTH_LONG).show();
                    finish();
                }
                break;
            case BaseResp.ErrCode.ERR_SENT_FAILED:
                if(resp.toString().contains("com.tencent.mm.opensdk.modelmsg.SendMessageToWX$Resp")){
                    MyLog.e("微信","分享失败");
                    ContentDataBean.DataBean textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {}.getType());
                    if (textContent != null) {
                        Toast.makeText(WXEntryActivity.this, textContent.getShare_error(), Toast.LENGTH_LONG).show();
                    }
                    finish();
                }else {
                    MyLog.e("微信","登录失败");
//                    Toast.makeText(WXEntryActivity.this,getString(R.string.login_fail),Toast.LENGTH_LONG).show();
                    finish();
                }
                break;
            default:
                break;
        }
    }

    private void goToGetMsg() {
        finish();
    }

    private void goToShowMsg(ShowMessageFromWX.Req showReq) {
        WXMediaMessage wxMsg = showReq.message;
        WXAppExtendObject obj = (WXAppExtendObject) wxMsg.mediaObject;
        StringBuffer msg = new StringBuffer(); // 组织一个待显示的消息内容
        msg.append("description: ");
        msg.append(wxMsg.description);
        msg.append("\n");
        msg.append("extInfo: ");
        msg.append(obj.extInfo);
        msg.append("\n");
        msg.append("filePath: ");
        msg.append(obj.filePath);
        finish();
    }

    /**
     * 获取微信OpenId
     */
    private void getWxOpenId(String code) {

        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("appid", getString(R.string.weixin_appid));
        paramsMap.put("secret", getString(R.string.weixin_app_secret));
        paramsMap.put("code", code);
        paramsMap.put("grant_type", "authorization_code");
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_GET, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
//                {"code":1,"msg":"发送成功","time":"1571105679","data":8851}
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    openidWX = jsonObject.getString("openid");

                    msg.arg1 = 2;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });

    }
    /**
     * 获取微信
     */
    private void getcode(String openid) {
        MyLog.e("微信openid",openid+"   微信开放平台");

        String url = myApp.getWebConfig()+"/api/user/wechatlogin";
        HashMap<String, String> paramsMap = new HashMap<>();
//        paramsMap.put("appid", "wxb502a998596ce7de");
//        paramsMap.put("secret", "96c1f3ef4626a82b2d3003fd5526b5ca");
        paramsMap.put("openid", openid);
        paramsMap.put("is_material", apptype);
//        paramsMap.put("grant_type", "authorization_code");
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
//                {"code":1,"msg":"发送成功","time":"1571105679","data":8851}
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    dataFB = jsonObject.getJSONObject("data");
                    status = dataFB.getString("status");
                    msg.arg1 = 3;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });

    }

    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            Intent intent = null;
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    String str = (String) msg.obj;
                    Toast.makeText(context, str, Toast.LENGTH_LONG).show();
                    break;
                case 1:
                    ContentDataBean.DataBean textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {}.getType());
                    if (textContent != null) {
                        Toast.makeText(WXEntryActivity.this, textContent.getNet_error(), Toast.LENGTH_LONG).show();
                    }
                    break;
                case 2:

                    getcode(openidWX);
                    break;
                case 3:
                    try {
                        if ("0".equals(status)){
                            intent = new Intent(context, LoginInputmsgActivity.class);
                            intent.putExtra("wxid",openidWX);
                            intent.putExtra("fbid","");
                            intent.putExtra("logintype","wx");
                            startActivity(intent);
                            finish();
                        }else if ("1".equals(status)){
                            JSONObject useri = dataFB.getJSONObject("userinfo");
                            SharedPreferences spuserInfo = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
                            spuserInfo.edit().putString("username", useri.getString("username")).commit();
                            spuserInfo.edit().putString("nickname", useri.getString("nickname")).commit();
                            spuserInfo.edit().putString("mobile", useri.getString("mobile")).commit();
                            spuserInfo.edit().putString("score", useri.getString("score")).commit();
                            spuserInfo.edit().putString("token", useri.getString("token")).commit();
                            spuserInfo.edit().putString("user_id", useri.getString("user_id")).commit();
                            spuserInfo.edit().putString("level", useri.getString("level")).commit();
                            String language =  PreferenceUtil.getString("language", "");
                            String templanuage = "";
                            if ("0".equals(useri.getString("language"))){
//                        spuserInfo.edit().putString("language", "zh").commit();
                                templanuage = "zh";
                            }else if ("1".equals(useri.getString("language"))){
                                templanuage = "en";
                            }else if ("2".equals(useri.getString("language"))){
                                templanuage = "ja";
                            }
                            if (!language.equals(templanuage)){
                                PreferenceUtil.commitString("language", language);
                            }
                            intent = new Intent(context, MainActivity.class);
                            startActivity(intent);
                            myApp.destoryActivity("登陆页面");
                            finish();
                        }
                    }catch (Exception e){

                    }
                    break;
                case 4:

                    break;
                case 5:


                    break;
            }
        }
    };

}